<?php

declare(strict_types=1);

namespace app\service\system;

use app\model\system\UserGroupModel;
use app\model\system\RoleModel;
use app\model\system\UserModel;
use owns\auth\UserAuth;
use owns\enum\SysEnum;

/**
 * 管理员
 */
class UserService
{
    protected $auth;

    public function __construct()
    {
        $this->auth = UserAuth::instance();
    }
    /**
     * 列表
     * @param array $param
     */
    public function list(array $param): array
    {
        $list = UserModel::custom($param)->user()
            ->with(['role', 'group'])
            ->pages($param)
            ->select();
        return list_fmt($list, UserModel::custom($param)->user()->count());
    }
    /**
     * 编辑
     * @param array $data
     * @param integer $id
     */
    public function edit(array $data, int $id): void
    {
        // 分组
        if (!UserGroupModel::find($data['group_id'])) {
            tips('未找到选择的分组信息');
        }
        // 角色
        if (!RoleModel::find($data['role_id'])) {
            tips('未找到选择的角色信息');
        }
        if ($id) {
            $user = UserModel::find($id);
            if (!$user) {
                tips('无管理员【' . $data['username'] . '】信息');
            }
            $user->updated_by = $this->auth->username();
        } else {
            $user = new UserModel();
            $user->username = trim($data['username']);
            $user->group_id = $data['group_id'];
            // 账号查重
            $this->_usernameRepeat(1, $user->username);
            $user->password = md5(trim($data['encryption'] ?: SysEnum::DEFAULT_PASS));
            $user->created_by = $this->auth->username();
        }
        if (!SysEnum::isSpecialAccount($id) || $this->auth->root()) {
            $user->phone = trim($data['phone']);
            $this->_usernameRepeat(2, $user->phone, $id);
            $user->nickname = trim($data['nickname']);
            $user->status = $data['status'];
        }
        $user->email = trim($data['email']);
        $user->avatar = $data['avatar'];
        $user->signed = $data['signed'];
        $user->dashboard = $data['dashboard'];
        $user->role_id = $data['role_id'];
        $user->remark = $data['remark'];
        if (!$user->save()) {
            tips('保存失败');
        }
    }
    /**
     * 账号或电话号码查重
     * @param integer $type 类型: 1.账户 2.手机号
     * @param string $keyword
     * @param integer $id
     */
    protected function _usernameRepeat(int $type, string $keyword, $id = 0): void
    {
        $where = UserModel::whereIn('status', [1, 2]);
        if ($type == 1) {
            $where->where('username', $keyword);
        } else {
            $where->where('phone', $keyword);
        }
        if ($id) {
            $where->where('id', '<>', $id);
        }
        if ($where->find()) {
            tips(($type == 1 ? '用户名' : '手机号') . '【' . $keyword . '】已被使用');
        }
    }
    /**
     * 用户密码重置
     * @param array $param
     */
    public function resetPassword(array $param): bool
    {
        $updata = [
            'password' => md5($param['encryption']),
            'updated_by' => $this->auth->username()
        ];
        return UserModel::whereIn('id', $param['ids'])->update($updata) ? true : false;
    }
    /**
     * 删除
     * @param integer $id 管理员id
     */
    public function delete(int $id): bool
    {
        if (SysEnum::isSpecialAccount($id)) {
            tips('无权限');
        }
        return UserModel::where('id', $id)->delete();
    }
    /**
     * 修改状态
     * @param integer $id 管理员id
     */
    public function status(int $id): bool
    {
        $user = UserModel::find($id);
        if (!$user) {
            tips('无管理员信息');
        }
        $user->status = $user->status ? 0 : 1;
        $user->created_by = $this->auth->username();
        return $user->save();
    }
    /**
     * 修改秘密
     * @param array $param
     */
    public function modifyPassword(array $param): bool
    {
        $user = UserModel::find($this->auth->uid());
        if (!$user) {
            tips('修改密码失败');
        }
        if ($user->password != md5($param['userPassword'])) {
            tips('密码不正确，修改失败');
        }
        $user->password = md5($param['confirmNewPassword']);
        return $user->save();
    }
    /**
     * 修改个人信息
     * @param array $param
     */
    public function modifyUser(array $param): bool
    {
        $user = UserModel::find($this->auth->uid());
        if (!$user) {
            tips('修改个人信息失败');
        }
        $user->nickname = trim($param['nickname']);
        $user->sex = $param['sex'];
        $user->email = trim($param['email'] ?? '');
        $user->signed = $param['signed'];
        return $user->save();
    }
}
